﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VigenereCipher.Models
{
    /// <summary>
    /// 加密类
    /// </summary>
    internal class EncryModel
    {
        /// <summary>
        /// 明文
        /// </summary>
        public string EncryPlainText { get; set; }

        /// <summary>
        /// 密文
        /// </summary>
        public string EncryCipher { get; set; }

        /// <summary>
        /// 密钥
        /// </summary>
        public string EncryKey { get; set; }

        /// <summary>
        /// 加密过程
        /// </summary>
        public void Encode()
        {
            int length = EncryKey.Length;
            char[] encryPlainText = EncryPlainText.ToCharArray();
            char[] encryKey = EncryKey.ToCharArray();
            char[] encryCipher = new char[EncryPlainText.Length];
            //加密
            for (int i = 0; i < encryPlainText.Length; i++)
            {
                char ch='0';
                int result = (GetNum(encryPlainText[i]) + GetNum(encryKey[i % length])) % 26;
                if ('a' <= encryPlainText[i] && encryPlainText[i] <= 'z')
                {
                    ch = Convert.ToChar(result + 'A');
                }
                if ('A' <= encryPlainText[i] && encryPlainText[i] <= 'Z')
                {
                    ch = Convert.ToChar(result + 'a');
                }
                encryCipher[i] = ch;
            }
            EncryCipher = new string(encryCipher);

        }

        /// <summary>
        /// 返回指定字符在字母表中的序号（从0开始）
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private int GetNum(char ch)
        {
            int result = 0;
            if ('a' <= ch && ch <= 'z')
            { result = ch - 'a'; }
            if ('A' <= ch && ch <= 'Z')
            { result = ch - 'A'; }
            return result;
        }

    }
}
